//
import VueRouter from 'vue-router'
import JWTToken from './helpers/jwt'

let routes = [{
    path: '/',
    name: 'index',
    component: require('./components/pages/Home').default,
    meta: {}
  },
  {
    path: '/about',
    name: 'about',
    component: require('./components/pages/About').default,
    meta: {}
  }, {
    path: '/posts/:id',
    name: 'posts',
    component: require('./components/posts/Post').default,
    meta: {}
  }, {
    path: '/register',
    name: 'register',
    component: require('./components/register/Register').default,
    meta: {
      requiresGuest: true
    }
  }, {
    path: '/confirm',
    name: 'confirm',
    component: require('./components/confirm/Email').default,
    meta: {}
  }, {
    path: '/login',
    name: 'login',
    component: require('./components/login/Login').default,
    meta: {
      requiresGuest: true
    }
  }, {
    path: '/profile',
    component: require('./components/user/ProfileWrapper').default,
    children: [{
        path: '',
        name: 'profile',
        component: require('./components/user/Profile').default,
        meta: {
          requiresAuth: true
        }
      }, {
        path: 'edit-profile',
        name: 'profile.edit',
        component: require('./components/user/ProfileEdit').default,
        meta: {
          requiresAuth: true
        }
      },
      {
        path: 'edit-password',
        name: 'password.edit',
        component: require('./components/user/PasswordEdit').default,
        meta: {
          requiresAuth: true
        }
      },
    ],
    meta: {
      requiresAuth: true
    }
  }
]


let router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  let userIsLogin = !!JWTToken.getToken()
  if (to.meta.requiresAuth) {
    if (!userIsLogin) {
      return next({
        name: 'login'
      })
    }
  }
  if (to.meta.requiresGuest) {
    if (userIsLogin) {
      return next({
        name: 'index'
      })
    }
  }
  next()
})

export default router
